<!--
 * @Description: 人员费用记录页面
-->
<template>
  <BaseMainSlot>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="73"
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :has-edit="false"
        :has-save="false"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        @add="add"
        @cancel="cancel('formData')"
        @edit="edit"
        @del="del"
        @save="save('formData')"
      />
    </template>
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
      <!-- <SearchBox @search="search">
        <div class="common-search-item">
          <div class="label label-80">人员名称:</div>
          <div class="input">
            <el-select v-model="personNo" filterable clearable>
              <el-option
                v-for="item in StaffData"
                :key="item.person.personNo"
                :label="item.person.name"
                :value="item.person.personNo"
              />
            </el-select>
          </div>
        </div>
        <div class="common-search-item">
          <div class="label label-80">时间选择:</div>
          <div class="input">
            <StartTimeEndTimeSelectionBox
              @startVal="startVal"
              @endVal="endVal"
            />
          </div>
        </div>
      </SearchBox> -->
    </template>
    <template v-slot:table-box>
      <el-table
        id="out-table"
        ref="tableData"
        v-loading="loading"
        highlight-current-row
        :data="tableData"
        stripe
        border
        height="88%"
        @row-click="handleEdit"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="55" />
        <el-table-column prop="employeeName" label="人员名称" />
        <el-table-column prop="basicSalary" label="基本工资(元)" />
        <!-- <el-table-column prop="socialSecurity" label="社保" /> -->
        <!-- <el-table-column prop="bonus" label="奖金" /> -->
        <!-- <el-table-column prop="subsidies" label="其他补贴" /> -->
        <el-table-column prop="deductionsAmount" label="扣除金额(元)" />
        <el-table-column prop="actualAmount" label="实发金额(元)" />
        <el-table-column prop="attendanceDays" label="出勤天数" />
        <el-table-column prop="offDays" label="请假天数" />
        <el-table-column
          prop="paymentTime"
          :formatter="dateFormat"
          label="发放时间"
          min-width="120"
        />
        <el-table-column width="200" label="操作">
          <template v-if="scope.row.personNo" slot-scope="scope">
            <el-button
              v-if="judgePermission(73, 'edit')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="edit"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button
              v-if="judgePermission(73, 'delete')"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="handleDelete(scope.row.personnelExpensesId)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="titleText + '人员费用信息'"
        :visible.sync="dialogFormVisible"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item label="人员名称:" prop="personNo" class="w50p">
            <el-select
              v-model="formData.personNo"
              clearable
              filterable
              :disabled="!canInput"
            >
              <el-option
                v-for="item in StaffData"
                :key="item.person.personNo"
                :label="item.person.name"
                :value="item.person.personNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="基本工资(元):" prop="basicSalary" class="w50p">
            <el-input
              v-model="formData.basicSalary"
              :disabled="!canInput"
              placeholder="请输入基本工资"
              clearable
            />
          </el-form-item>
          <!-- <el-form-item label="社保:" prop="socialSecurity" class="w50p">
          <el-input
            v-model="formData.socialSecurity"
            :disabled="!canInput"
            placeholder=""
            clearable
          />
          </el-form-item>-->
          <el-form-item label="奖金及补贴(元):" prop="bonus" class="w50p">
            <el-input
              v-model="formData.bonus"
              :disabled="!canInput"
              placeholder="请输入奖金及补贴"
              clearable
            />
          </el-form-item>
          <!-- <el-form-item label="其他补贴:" prop="subsidies" class="w50p">
          <el-input
            v-model="formData.subsidies"
            :disabled="!canInput"
            placeholder=""
            clearable
          />
          </el-form-item>-->
          <el-form-item label="代扣费用(元):" prop="deductionsAmount" class="w50p">
            <el-input
              v-model="formData.deductionsAmount"
              :disabled="!canInput"
              placeholder="请输入代扣费用"
              clearable
            />
          </el-form-item>
          <el-form-item label="实发金额(元):" prop="actualAmount" class="w50p">
            <el-input
              :value="formData.actualAmount"
              placeholder="实发金额根据工资、奖金及补贴、代扣费用"
              :disabled="!canInput"
              clearable
            />
          </el-form-item>
          <el-form-item label="出勤天数:" prop="attendanceDays" class="w50p">
            <el-input
              v-model="formData.attendanceDays"
              :disabled="!canInput"
              placeholder="请输入出勤天数"
              clearable
            />
          </el-form-item>
          <el-form-item label="请假天数:" prop="offDays" class="w50p">
            <el-input
              v-model="formData.offDays"
              :disabled="!canInput"
              placeholder="请输入请假天数(无请假请输入0)"
              clearable
            />
          </el-form-item>
          <el-form-item label="发放时间:" prop="paymentTime" class="w50p">
            <el-date-picker
              v-model="formData.paymentTime"
              type="datetime"
              value-format="timestamp"
              :disabled="!canInput"
              placeholder="请选择发放时间"
              clearable
            />
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import SearchForm from '@/components/searchForm';
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import PersonnelCostRecord from "@/api/digital-operation/personnel-cost-mansge/personnel-cost-record/index";
import StartTimeEndTimeSelectionBox from "@/components/StartTimeEndTimeSelectionBox";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";
// import { compile } from 'path-to-regexp';

export default {
  name: "PersonnelCostRecord",
  components: {
    SearchForm,
    ActionBar,
    Pagination,
    BaseMainSlot,
    StartTimeEndTimeSelectionBox,
  },
  mixins: [mymixin],
  data() {
    return {
      formConfig: [
        {
          label: '人员名称',
          prop: 'personNo',
          type: 'select',
          options: [], // StaffData
          optionKey: { label: 'personName', value: 'personNo' },
        }, {
          label: '时间选择',
          prop: 'date',
          type: 'daterange',
        },
      ],
      searchlist: {},
      // 时间搜索
      startTime: "",
      endTime: "",
      // 选中的数据项数组 personNo组成 (此数组最多为一个)
      personNoList: [],
      StaffData: [],
      personNo: "",
      rules: {
        personNo: [
          { required: true, message: "请选择人员名称", trigger: "change" }
        ],
        basicSalary: [
          { required: true, message: "请输入基本工资(元)", trigger: "blur" },
          {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: "请输入数字",
            trigger: "blur"
          }
        ],
        bonus: [
          { required: true, message: "请输入奖金及补贴(元)", trigger: "blur" },
          {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: "请输入数字",
            trigger: "blur"
          }
        ],
        deductionsAmount: [
          { required: true, message: "请输入代扣费用(元)", trigger: "blur" },
          {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: "请输入数字",
            trigger: "blur"
          }
        ],
        attendanceDays: [
          { required: true, message: "请输入出勤天数", trigger: "blur" },
          {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: "请输入数字",
            trigger: "blur"
          }
        ],
        offDays: [
          { required: true, message: "请输入请假天数", trigger: "blur" },
          {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: "请输入数字",
            trigger: "blur"
          }
        ],
        paymentTime: [
          { required: true, message: "请选择时间", trigger: "change" }
        ]
      }
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    formData: {
      handler(val) {
        // 判断input值改变时才触发
        if (val.basicSalary && val.bonus && val.deductionsAmount) {
          // 当input值改变时计算
          this.$set(
            val,
            "actualAmount",
            (
              parseFloat(val.basicSalary) +
              parseFloat(val.bonus) -
              parseFloat(val.deductionsAmount)
            ).toFixed(2)
          );
        }
      },
      deep: true
    }
  },
  mounted() {
    //  表格数据
    this.getTableDataList();
    this.queryDataList();
  },
  methods: {
    getTableDataList() {
      let param = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          organizationNo: sessionStorage.organizationNo,
          personNo: this.searchlist.personNo,
          startTime: this.searchlist.date && this.dateToFormattwo(this.searchlist.date[0]),
          endTime: this.searchlist.date && this.dateToFormattwo(this.searchlist.date[1]),
          // startTime: this.startTime,
          // endTime: this.endTime
        }
      };
      // console.log(param);
      PersonnelCostRecord.queryPersonnelVariety(param).then(res => {
        this.loading = false;
        let data = res.data;
        // console.log(data)
        if (data) {
          this.totalSize = data.totalElements;
          this.tableData = data.content;
          this.addblankmet();
          this.resetActionBar();
          this.$refs.formData.resetFields();
        }
      });
      this.resetActionBar();
    },
    async queryDataList() {
      // 员工
      const {
        data: Staff
      } = await PersonnelCostRecord.getStaffListByCondition();
      this.StaffData = Staff;
      let list = Staff.map(el => {
        return { ...el, personName: el.person.name }
      })
      this.setOptions(this.formConfig, 'personNo', list)
    },
    // 点击导出搜索的数据
    async ExpensesDownExcel() {
      let params = {
        personNo: this.searchlist.personNo,
          startTime: this.searchlist.date && this.dateToFormattwo(this.searchlist.date[0]),
          endTime: this.searchlist.date && this.dateToFormattwo(this.searchlist.date[1]),
        organizationNo: parseInt(sessionStorage.organizationNo)
      };
      let param = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          // organizationNo: sessionStorage.organizationNo,
          personNo: this.searchlist.personNo,
          // startTime: this.startTime,
          // endTime: this.endTime,
          startTime: this.searchlist.date && this.dateToFormattwo(this.searchlist.date[0]),
          endTime: this.searchlist.date && this.dateToFormattwo(this.searchlist.date[1]),
          organizationNo: parseInt(sessionStorage.organizationNo)
        }
      };
      // let data = params
      const data = await PersonnelCostRecord.personnelExpensesDownExcel(params);
      // if (params.personNo || params.startTime && params.endTime) {
      // let tableDataList = []
      const { data: res } = await PersonnelCostRecord.queryPersonnelVariety(
        param
      );
      if (!res.content.length > 0) return this.$message.warning("暂无导出数据");
      const blob = new Blob([data], {
        type: "application/vnd.ms-excel;charset=utf-8"
      });
      const link = document.createElement("a");
      link.download = "人员费用记录表.xls";
      link.style.display = "none";
      link.href = URL.createObjectURL(blob);
      document.body.appendChild(link);
      link.click();
      URL.revokeObjectURL(link.href);
      document.body.removeChild(link);
      // } else if (!params.personNo || !params.startTime && !params.endTime) {
      // this.$message.warning('请选择名称或者时间!')
      // }
    },
    // 时间转换
    dateFormat(row, colnum) {
      if (row.personNo) {
        return this.$moment(row[colnum.property]).format("YYYY-MM-DD HH:mm:ss");
      }
    },
    // 搜索框时间
    startVal(e) {
      this.startTime = e;
    },
    endVal(e) {
      this.endTime = e;
    },
    // 表格
    search() {
      this.currentPage = 1;
      // console.log(this.personNo);
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    handleEdit(row) {
      // console.log(row);
      // TODO 点击行元素后 edit
      this.formData = JSON.parse(JSON.stringify(row));
      // this.addActive = false;
      this.editActive = true;
      this.saveActive = false;
      this.cancelActive = true;
      // this.canInput = false;
      // this.$refs.formData.resetFields()
    },
    handleSelectionChange(list) {
      this.personNoList = [];
      this.personNoList = list.map(item => item.personnelExpensesId);
      // console.log(this.personNoList);
      if (this.personNoList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      PersonnelCostRecord.delPersonnelExpensesInfo(this.personNoList).then(
        res => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.getTableDataList();
          } else {
            this.$message.warning(res.msg || "删除失败");
          }
        }
      );
      this.resetActionBar();
    },
    handleDelete(val) {
      // PersonnelCostRecord.delExpensesInfo(val).then(res => {
      //   if (res.code === 1) {
      //     this.$message.success(res.msg);
      //     this.getTableDataList();
      //   } else {
      //     this.$message.warning(res.msg || "删除失败");
      //   }
      // });
      // this.selectedStaffList.splice(0, this.selectedStaffList.length - 1);
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          PersonnelCostRecord.delExpensesInfo(val).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.getTableDataList();
            } else {
              this.$message.warning(res.msg || "删除失败");
            }
          });
        })
        .catch(() => {
          this.$message("取消删除");
        });
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            // console.log(this.formData)
            // this.formData.organizationNo = sessionStorage.organizationNo

            PersonnelCostRecord.editInspectionRouteInfo(this.formData).then(
              res => {
                if (res.code === 1) {
                  this.$message.success(res.msg || "修改成功！");
                  this.$refs[formData].resetFields();
                  this.getTableDataList();
                } else {
                  this.$message.error(res.msg || "修改失败！");
                }
              }
            );
          } else if (this.nowChanceStau === "add") {
            // if (this.formData.personNo) {
            //   delete this.formData.personNo
            // }
            this.formData.organizationNo = sessionStorage.organizationNo;
            PersonnelCostRecord.addPersonnelExpensesInfo(this.formData).then(
              res => {
                if (res.code === 1) {
                  this.$message.success(res.msg || "新增成功！");
                  this.$refs[formData].resetFields();
                  this.getTableDataList();
                } else {
                  this.$message.error(res.msg || "新增失败！");
                }
              }
            );
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-form-item__label {
  min-width: 140px !important;
}
.DownExcel {
  margin-left: 20px;
  // background-color: #03bfef;
  // // border: 1px solid ;
}
</style>
